import { computed, ref, watch } from 'vue'
import { onPageScroll } from '@dcloudio/uni-app'
import { hexToRgba, parseNumber } from '../utils'

let w

export const useBgColorFadeIn = (style, nh) => {
  const opacity = ref(0)

  if (w) w()

  w = watch(
    () => nh.value,
    (nh) => {
      onPageScroll(({ scrollTop }) => {
        const s = parseNumber(scrollTop / nh)
        opacity.value = s >= 1 ? 1 : s
      })
    },
    { immediate: true, deep: true }
  )

  const color = computed(() => {
    const c = style.value?.backgroundColor || '#ffffff'
    const rgba = hexToRgba(c, opacity.value)
    const result = {
      color: rgba.rgba,
      opacity: opacity.value
    }

    return result
  })

  return color
}
